package com.psmz.iwi.docanalyzer.ui;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import com.psmz.iwi.docanalyzer.core.document.business.DocumentRepositoryService;
import com.psmz.iwi.docanalyzer.core.document.business.DocumentRepositoryServiceException;
import com.psmz.iwi.docanalyzer.core.document.entities.DocumentSearchResult;
import com.psmz.iwi.docanalyzer.core.document.entities.NumberOfWordsClassificationGroup;
import com.psmz.iwi.docanalyzer.core.document.job.DocumentIndexingJob;
import com.psmz.iwi.docanalyzer.core.settings.ApplicationSettings;

public class MainFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4038103014001353905L;
	private JPanel contentPane;
	private ApplicationSettings settings;
	private ResultTableModel tableModel;
	private JTextField searchTextField;
	private JLabel indexingStatusLabel = new JLabel("Bezczynny");
	private JTable resultTable;
	private ClassifiedDocumentsTreeModel treeModel;

	/**
	 * Create the frame.
	 */
	public MainFrame(ApplicationSettings settings) {
		List<DocumentSearchResult> emptyList = new ArrayList<DocumentSearchResult>();
		DocumentRepositoryService repositoryService = new DocumentRepositoryService(
				settings);
		try {
			List<NumberOfWordsClassificationGroup> classifiedDocuments = repositoryService
					.getClassifiedDocuments();
			treeModel = new ClassifiedDocumentsTreeModel(classifiedDocuments);
		} catch (DocumentRepositoryServiceException e2) {
			JOptionPane.showMessageDialog(MainFrame.this,
					"Blad pobierania danych,  powod: " + e2.toString(), "Blad",
					JOptionPane.ERROR_MESSAGE);
		}
		emptyList.add(new DocumentSearchResult());
		tableModel = new ResultTableModel(emptyList);
		setResizable(false);
		this.settings = settings;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 591, 456);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu actionMenu = new JMenu("Operacje");
		menuBar.add(actionMenu);

		JMenuItem indexItem = new JMenuItem("Zaladuj katalog");
		indexItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int dialogResult = chooser.showOpenDialog(MainFrame.this);
				if (dialogResult == JFileChooser.APPROVE_OPTION) {
					File selectedFile = chooser.getSelectedFile();
					DocumentRepositoryService repositoryService = new DocumentRepositoryService(
							MainFrame.this.settings);
					try {
						indexingStatusLabel.setText("Trwa ladowanie danych");
						DisabledGlassPane glassPane = new DisabledGlassPane();
						MainFrame.this.getRootPane().setGlassPane(glassPane);
						glassPane.activate("Trwa ładowanie danych do bazy");
						repositoryService.storeDocuments(
								selectedFile.getAbsolutePath(), new Observer() {

									@Override
									public void update(Observable o, Object arg) {
										if (arg instanceof Integer) {
											int argument = (Integer) arg;

											switch (argument) {
											case DocumentIndexingJob.START_NOTIFICATION:

												indexingStatusLabel
														.setText("Indeksowanie rozpoczete");
												indexingStatusLabel.validate();
												break;

											case DocumentIndexingJob.FAILED_NOTIFICATION:

												indexingStatusLabel
														.setText("Indeksowanie nieudane");
												indexingStatusLabel.validate();
												break;

											case DocumentIndexingJob.FINISHED_NOTIFICATION:

												indexingStatusLabel
														.setText("Indeksowanie zakonczone");
												indexingStatusLabel.validate();
												break;

											default:
												break;

											}

										}
									}
								});
						glassPane.deactivate();
					} catch (DocumentRepositoryServiceException e1) {
						JOptionPane.showMessageDialog(
								MainFrame.this,
								"Blad ladowania danych,  powod: "
										+ e1.toString(), "Blad",
								JOptionPane.ERROR_MESSAGE);
					}

				}
			}
		});
		actionMenu.add(indexItem);
		JMenuItem exitMenuItem = new JMenuItem("Wyjscie");
		exitMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		actionMenu.add(exitMenuItem);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setBounds(0, 0, 585, 407);
		contentPane.add(tabbedPane);

		JPanel searchTabPanel = new JPanel();
		tabbedPane.addTab("Szukaj", null, searchTabPanel, null);
		searchTabPanel.setLayout(null);

		JLabel indexingStatusDescriptionLabel = new JLabel(
				"Status indeksowania:");
		indexingStatusDescriptionLabel.setBounds(10, 340, 111, 14);
		searchTabPanel.add(indexingStatusDescriptionLabel);

		indexingStatusLabel.setFont(new Font("Tahoma", Font.BOLD, 11));
		indexingStatusLabel.setBounds(10, 354, 153, 14);
		searchTabPanel.add(indexingStatusLabel);

		searchTextField = new JTextField();
		searchTextField.setBounds(10, 11, 454, 20);
		searchTabPanel.add(searchTextField);
		searchTextField.setColumns(10);

		JButton searchButton = new JButton("Wyszukaj");
		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				DocumentRepositoryService repositoryService = new DocumentRepositoryService(
						MainFrame.this.settings);
				try {
					String phrase = searchTextField.getText();
					Collection<DocumentSearchResult> results = repositoryService
							.documentFullTextSearch(phrase.trim());
					tableModel.reloadData(results);
				} catch (DocumentRepositoryServiceException e1) {
					JOptionPane.showMessageDialog(MainFrame.this,
							"Blad wyszukiwania, powod: " + e1.toString(),
							"Blad", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		searchButton.setBounds(474, 10, 89, 23);
		searchTabPanel.add(searchButton);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 70, 553, 247);
		searchTabPanel.add(scrollPane);

		resultTable = new JTable(tableModel);
		scrollPane.setViewportView(resultTable);

		Panel exploreTabPanel = new Panel();
		tabbedPane.addTab("Przeglądaj", null, exploreTabPanel, null);
		exploreTabPanel.setLayout(new BorderLayout(0, 0));

		JPanel functionButtonPanel = new JPanel();
		exploreTabPanel.add(functionButtonPanel, BorderLayout.NORTH);
		functionButtonPanel.setLayout(new BorderLayout(0, 0));

		JButton refreshButton = new JButton("Odśwież");
		refreshButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					DocumentRepositoryService repositoryService = new DocumentRepositoryService(
							MainFrame.this.settings);
					List<NumberOfWordsClassificationGroup> classifiedDocuments = repositoryService
							.getClassifiedDocuments();
					treeModel.reloadData(classifiedDocuments);
				} catch (DocumentRepositoryServiceException e2) {
					JOptionPane.showMessageDialog(MainFrame.this,
							"Blad pobierania danych,  powod: " + e2.toString(),
							"Blad", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		refreshButton.setHorizontalAlignment(SwingConstants.LEFT);
		functionButtonPanel.add(refreshButton, BorderLayout.WEST);

		JScrollPane treeScrollPane = new JScrollPane();
		exploreTabPanel.add(treeScrollPane, BorderLayout.CENTER);

		JTree tree = new JTree(treeModel);
		treeScrollPane.setViewportView(tree);
	}
}
